<?php

namespace App\Http\Controllers\H5;
use App\Library\User\CommissionManager;
use App\Models\CommissionRecords;
use App\Models\Order;
use App\Models\User;
use App\Models\Usermemberlevel;
use App\Models\Accoutrecord;
use App\Models\Apointccount;
use App\Models\Bankaccount;
use App\Models\UserRelation;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CommissionController extends BaseController
{
    public function index()
    {
        //我的佣金
        $wallet = $this->user()->wallet()->firstOrCreate([]);
        $totalAchievement = $wallet->total_cost;
        $totalCommission = $wallet->commission;


        $teams = [];
        foreach (UserRelation::where('upuid', $this->uid)->get() as $relation)
        {
            $teams[] = $relation->uid;
        }

        foreach (UserRelation::whereIn('upuid', $teams)->get() as $relation)
        {
            $teams[] = $relation->uid;
        }

        if (!empty($teams))
        {
            $users = User::with('wallet')->whereIn('uid', $teams)->get();
            foreach ($users as $user)
            {
                $totalAchievement+= $user->wallet->total_cost;
                $totalCommission+= $user->wallet->commission;
            }
        }

        return $this->view('h5.commission.index', compact('wallet', 'totalAchievement', 'totalCommission'));
    }

    public function getRecords(Request $request)
    {
        $offset = $request->input('offset', 0);
        $count  = $request->input('count', 10);
        $type   = $request->input('type', 'all');

        $query = $this->user()->commissionRecords();
        if ($type == 'income')
        {
            $query = $query->where('trade_type', 1);
        } elseif ($type == 'withdraw') {
            $query = $query->where('trade_type', 0);
        }

        $items = $query->offset($offset)->limit($count)->orderByDesc('id')->get();
        return ajaxReturn(['items'=>$items]);
    }

    public function showRecord(Request $request)
    {

        $id = $request->input('id');
        $record = $this->user()->commissionRecords()->find($id);
        $order  = $record->order;
        if (!$order)
        {
            return $this->messager()->message('订单信息已被删除')->render();
        }
        $buyer  = $order->buyer;

        if ($record->type == 1)
        {
            $uprecord = CommissionRecords::where('order_id', $order->order_id)->where('type', 2)->first();
            if ($uprecord)
            {
                $uper = $uprecord->user;
            } else {
                $uper = null;
            }

        } else {
            $uprecord = null;
            $uper = null;
        }

        if ($record->type == 2)
        {
            $subrecord = CommissionRecords::where('order_id', $order->order_id)->where('type', 1)->first();
            if ($subrecord)
            {
                $suber = $subrecord->user;
            } else {
                $suber = null;
            }

        } else {
            $subrecord = null;
            $suber = null;
        }

        return $this->view('h5.commission.showrecord', compact('record', 'order', 'buyer', 'uper', 'suber', 'uprecord', 'subrecord'));
    }

    /**
     * 余额提现申请
     */
    public function showApplyWithdrawForm()
    {
        $withdraw = $this->user()->commissionWithdraws()->orderByDesc('id')->first();
        if ($withdraw)
        {
            if (date('Ymd') == @date('Ymd', $withdraw->created_at))
            {
                return $this->messager()->message('今日已提现')->tips('每位用户每天只能申请一次提现，金额不少于100元')->render();
            }
        }
        $wallet = $this->user()->wallet()->firstOrCreate([]);
        return $this->view('h5.commission.withdrawform', compact('wallet'));
    }

    public function storeApplyWithdraw(Request $request)
    {
        $card_id = $request->input('card_id');
        $amount  = $request->input('amount');

        if (CommissionManager::takeOffCommission($this->user(), $amount, '会员申请佣金提现')){
            $this->user()->commissionWithdraws()->create([
                'card_id'=>$card_id,
                'amount'=>$amount,
                'status'=>0
            ]);
        }

        return ajaxReturn();
    }

    /**
     * 余额提现记录
     */
    public function withdraw()
    {
        $wallet = $this->user()->wallet()->firstOrCreate([]);
        return $this->view('h5.commission.withdraw', compact('wallet'));
    }

    public function getWithdraws(Request $request)
    {
        $offset = $request->input('offset', 0);
        $count  = $request->input('count', 10);

        $items = $this->user()->commissionWithdraws()->with('card')->offset($offset)->limit($count)->orderBy('id')->get();
        return ajaxReturn(['items'=>$items]);
    }

    /**
     * 佣金和业绩记录
     */
    public function achievement()
    {
        return $this->view('h5.commission.achievement');
    }

    public function getAchievements(Request $request)
    {
        $items = $this->user()->Achievements()->orderByDesc('id')
            ->limit(30)->get()->map(function ($item){
                $item->date = @date('Y-m-d', $item->created_at);
                return $item;
            });
        return ajaxReturn(['items'=>$items]);
    }

}
